package com.hyx.bookManager.utils;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import net.minidev.json.JSONObject;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TokenUtil
 * @Description TODO
 * @Author 黄乙轩
 * @Date 2021/5/8 11:09
 * @Version 1.0
 **/

@Component
public class TokenUtil {
    private final byte[] secret = "geibosssoftsfdjsikolkjikolkijswm".getBytes();

    public String getTokenHS256(Map<String,Object> payloadMap) throws JOSEException {
        JWSHeader jwsHeader = new JWSHeader((JWSAlgorithm.HS256));
        Payload payload = new Payload(new JSONObject(payloadMap));
        JWSObject jwsObject = new JWSObject(jwsHeader,payload);

        JWSSigner jwsSigner = new MACSigner(secret);
        jwsObject.sign(jwsSigner);

        return jwsObject.serialize();
    }

    public Map<String,Object> validHS256(String token) throws ParseException, JOSEException {
        JWSObject jwsObject = JWSObject.parse(token);
        JWSVerifier jwsVerifier = new MACVerifier(secret);
        return verify(jwsObject,jwsVerifier);
    }

    private Map<String,Object> verify(JWSObject jwsObject,JWSVerifier jwsVerifier) throws JOSEException {
        Map<String,Object> resultMap = new HashMap<>();

        Payload payload = jwsObject.getPayload();

        if(jwsObject.verify(jwsVerifier)){
            resultMap.put("Result",0);
            JSONObject jsonObject = payload.toJSONObject();
            resultMap.put("data",jsonObject);
            if(jsonObject.containsKey("exp")){
                Long expTime = Long.valueOf(jsonObject.get("exp").toString());
                Long nowTime = System.currentTimeMillis();
                //判断是否过期
                if (nowTime > expTime) {
                    //已经过期
                    resultMap.clear();
                    resultMap.put("Result", 2);
                }
            }
        }else{
            resultMap.put("Result",1);
        }
        return resultMap;
    }
}
